package com.doys.myfirstapp;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.Toast;
import com.U8.UHFApplication;
import com.U8.model.Message;
import com.U8.model.ResponseHandler;
import com.U8.operation.U8Series;
import com.U8.reader.model.InventoryBuffer;
import com.U8.reader.server.ReaderHelper;
import com.U8.utils.MusicPlayer;
import com.doys.myfirstapp.u8.InventoryFragment;
import com.doys.myfirstapp.u8.U8Series2;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @ Author     ：wyt
 * @ Date       ：Created in 17:00 2021/4/20
 * @ Description： 可被调用的后端代码
 */
public class JSInterface extends Fragment implements View.OnClickListener {
    private String TAG = "JSInterface";
    private String model = "U8";
    public static Context context;
    public static Activity activity;
    public static SoundUtils soundUtils;
    private Handler mHandler;
    public static boolean isInventory;
    private static InventoryBuffer m_curInventoryBuffer = null;
    private String stringTxtRealInventoryCount = "";
    private ReaderHelper mReaderHelper;
    private long mRefreshTime;
    private int inventoryTimeHistory = 0;

    private List<InventoryBuffer.InventoryTagMap> inventoryTagData = new ArrayList<InventoryBuffer.InventoryTagMap>();


    public void init() {
//        InventoryFragment.context = context;
        Log.e("JSInterface","init");
    }

    // 定义JS需要调用的方法
    // 被JS调用的方法必须加入@JavascriptInterface注解
    @JavascriptInterface
    /**
    * @Description：  rfid扫描枪开始扫描
    * @Author wyt
    * @Date 2021/4/20
    */
    public void scanBegin() {
//        this.init();
//        Toast.makeText(JSInterface.context,"开始盘询",Toast.LENGTH_LONG).show();
        Log.e("JSInterface","scanBegin");

        U8Series2.rfidList.clear();
        if (isInventory) {
            scanEnd();
        }

        ActivityBroadcast.powerOn();

        try {
            mReaderHelper = ReaderHelper.getDefaultHelper();
        } catch (Exception e) {
            e.printStackTrace();
        }
        m_curInventoryBuffer = mReaderHelper.getCurInventoryBuffer();

        mReaderHelper.clearInventoryTotal();
        m_curInventoryBuffer.clearTagMap();


        isInventory = true;
        mRefreshTime = new Date().getTime();

        ActivityBroadcast.mUSeries.startInventory(new ResponseHandler() {

            @Override
            public void onFailure(String msg) {
                super.onFailure(msg);
                Toast.makeText(JSInterface.context,"盘询失败,错误码:"+msg,Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(String msg, Object data, byte[] parameters) {
                super.onSuccess(msg, data, parameters);
                if (msg.equals(U8Series.REFRESHTEXT)) {
                    refreshText();
                } else if (msg.equals(U8Series.REFRESHLIST)) {
                    inventoryTagData.clear();
                    inventoryTagData.addAll((Collection<? extends InventoryBuffer.InventoryTagMap>) data);
//                    Toast.makeText(JSInterface.context,"标签数量："+m_curInventoryBuffer.lsTagList.size(),Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(JSInterface.context,"盘询失败,返回标识异常:"+msg,Toast.LENGTH_SHORT).show();
                }
            }
        });

//        mHandler.postDelayed(mRefreshRunnable, 500);
    }

    private Runnable mRefreshRunnable = new Runnable() {
        public void run() {
            refreshText();
            mHandler.postDelayed(this, 2000);
        }
    };

    // 定义JS需要调用的方法
    // 被JS调用的方法必须加入@JavascriptInterface注解
    @JavascriptInterface
    /**
     * @Description：  rfid扫描枪结束扫描
     * @Author wyt
     * @Date 2021/4/20
     */
    public String scanEnd() {
//        mHandler.removeCallbacks(mRefreshRunnable);
        Log.e("JSInterface","scanEnd inventoryTagData.size="+U8Series2.rfidList.size());
//        Toast.makeText(JSInterface.context,"scanEnd inventoryTagData.size="+rfidList.size(),Toast.LENGTH_SHORT).show();



        String rfid ="";
        Set<String> rfidList = new HashSet<String>();
        final List<InventoryBuffer.InventoryTagMap>  inventoryTagDataTmp = inventoryTagData;
        for(InventoryBuffer.InventoryTagMap tapMap : inventoryTagDataTmp) {
            rfid = tapMap.strEPC;
            rfid= rfid.replace(" ", "");
            /*int f4Index = rfid.lastIndexOf("F4");
            if (f4Index == -1) {
                Log.e("JSInterface","rfid格式错误，"+rfid);
                continue;
            }

            rfid = rfid.substring(f4Index);
            rfid=rfid.substring(0,11);*/
            //0000000000000F40004681360000000000000
            rfidList.add(rfid);
        }
        if (isInventory) ActivityBroadcast.mUSeries.stopInventory();
        isInventory = false;
        return join(rfidList.iterator(),",");
    }


    public static String join(Iterator<?> iterator, String separator) {
        if (iterator == null) {
            return null;
        } else if (!iterator.hasNext()) {
            return "";
        } else {
            Object first = iterator.next();
            if (!iterator.hasNext()) {
                return Objects.toString(first, "");
            } else {
                StringBuilder buf = new StringBuilder(256);
                if (first != null) {
                    buf.append(first);
                }

                while(iterator.hasNext()) {
                    if (separator != null) {
                        buf.append(separator);
                    }

                    Object obj = iterator.next();
                    if (obj != null) {
                        buf.append(obj);
                    }
                }

                return buf.toString();
            }
        }
    }


    public void refreshText() {
        long now = new Date().getTime();
        m_curInventoryBuffer = mReaderHelper.getCurInventoryBuffer();
        String text = String.format("已盘:%d个,累计:%d条,速度:%d个/秒,耗时:%d秒", m_curInventoryBuffer.lsTagList.size(), mReaderHelper.getInventoryTotal(), m_curInventoryBuffer.nReadRate, (now - mRefreshTime) / 1000 + inventoryTimeHistory);
        Toast.makeText(JSInterface.context,text,Toast.LENGTH_SHORT).show();
        SoundPool sp =  new SoundPool(10, AudioManager.STREAM_SYSTEM,0);
        sp.load(JSInterface.context,R.raw.scan_broad,1);

        sp.play(R.raw.scan_ok,1,1,0,0,1);

        //有点卡顿，暂时不通知
//        ActivityBroadcast.rfidScanMsgPush(text);
    }

    @Override
    public void onClick(View view) {

    }




    /**
     * @Description：  文本框扫描成功 scan_ok.wav
     * @Author wyt
     * @Date 2021/8/23
     */
    @JavascriptInterface
    public void scanOk() {
        MediaPlayer.create(JSInterface.context,R.raw.scan_ok).start();
    }

    /**
     * @Description：  文本框扫描失败 scan_error.wav
     * @Author wyt
     * @Date 2021/8/23
     */
    @JavascriptInterface
    public void scanError() {
//        Toast.makeText(JSInterface.context,"scanError 调用成功",Toast.LENGTH_SHORT).show();
        MediaPlayer.create(JSInterface.context,R.raw.scan_error).start();
    }

    /**
     * @Description：  文本框扫描成功 scan_success.mp3
     * @Author wyt
     * @Date 2021/8/23
     */
    @JavascriptInterface
    public void scanSuccess() {
//        Toast.makeText(JSInterface.context,"scanError 调用成功",Toast.LENGTH_SHORT).show();
        MediaPlayer.create(JSInterface.context,R.raw.scan_success).start();
    }


    /**
     * @Description：  通用消息、站内消息 msg.mp3
     * @Author wyt
     * @Date 2021/8/23
     */
    @JavascriptInterface
    public void playMsg() {
        MediaPlayer.create(JSInterface.context,R.raw.msg).start();
    }


    /**
     * @Description：  文本框扫描成功 scan_ok.wav
     * @Author wyt
     * @Date 2021/8/23
     */
    @JavascriptInterface
    public void openImgUpload() {
        PhotoUtils.takePicture(JSInterface.activity,null,0);
    }

    /**
     * @Description：  回退
     * @Author wyt
     * @Date 2021/8/23
     */
    @JavascriptInterface
    public void androidBack() {
        JSInterface.activity.onBackPressed();
    }
    /**
     * @Description：  服务器选择界面
     * @Author wyt
     * @Date 2021/8/23
     */
    @JavascriptInterface
    public void loadServerIndex() {
        Intent home = new Intent(Intent.ACTION_MAIN);
        home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        home.addCategory(Intent.CATEGORY_HOME);
        startActivity(home);
        //退出系统，不保存之前页面
        System.exit(0);
    }

}
